package com.hc.contorl;

import com.hc.pojo.TbUser;
import com.hc.service.TbUserService;
import com.hc.service.impl.TbUserServiceImpl;
import org.apache.commons.codec.digest.DigestUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(value="/userSave")
public class UserSaveContorller extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");

        long id=Long.parseLong(req.getParameter("id"));
        String username=req.getParameter("userName");
        String password=req.getParameter("password");
        String email=req.getParameter("email");
        String phone=req.getParameter("phone");
        TbUserService service=new TbUserServiceImpl();
        TbUser user=null;
        if(id>0){
            user=service.findById(id);
            String oldpassword=user.getPassword();
            if(password!=null&&(!password.equals(oldpassword))){
                password= DigestUtils.md5Hex(password);
            }
        }else{
            user=new TbUser();
            password= DigestUtils.md5Hex(password);
        }
        user.setUserName(username);
        user.setEmail(email);
        user.setPassword(password);
        user.setPhone(phone);
        System.out.println(user);
        String text=null;
        if(id>0){
            int line=service.updateTbUer(user);
            if(line>0){
               req.setAttribute("message","修改成功！");
            }else{
                req.setAttribute("message","修改失败！");
            }
        }else{
            boolean bool=service.addUser(user);
            if(bool){
                req.setAttribute("message","添加成功！");;
            }else{
                req.setAttribute("message","添加失败！");;
            }
        }
        req.getRequestDispatcher("/user_form.jsp").forward(req,resp);

    }
}
